package com.hello.booksale.configuration;

import com.hello.booksale.filter.JWTAuthenticationFilter;
import com.hello.booksale.filter.LoginAuthenticationFilter;
import com.hello.booksale.filter.RecaptchaFilter;
import com.hello.booksale.handler.MyAccessDeniedHandler;
import com.hello.booksale.service.UserService;
import com.hello.booksale.util.JwtUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

import javax.annotation.Resource;

@Configuration
public class SecurityConfiguration{

    @Resource
    UserService userService;
    @Resource
    JwtUtil jwtUtil;
   @Resource
    AuthenticationManager authenticationManager;

    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .userDetailsService(userService)
                .authorizeRequests(authorize->authorize.mvcMatchers("/admin/**").hasRole("admin"))
                .authorizeRequests(authorize->authorize.mvcMatchers("/user/**").hasRole("user"))
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .permitAll()
                .usernameParameter("username")
                .passwordParameter("password")
                .and()
                .addFilter(new LoginAuthenticationFilter(authenticationManager,jwtUtil))
                .addFilter(new JWTAuthenticationFilter(authenticationManager,jwtUtil))
                .addFilterBefore(new RecaptchaFilter(),LoginAuthenticationFilter.class)
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new MyAccessDeniedHandler())
                .and()
                .logout()
                .deleteCookies("token")
                .logoutSuccessUrl("/login")
                .and()
                .build();
    }


}
